import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

import de.dhe.utils.FileHelper;
import de.preisrobot.entity.Artikel;
import de.preisrobot.service.helper.HttpClientFactory;
import de.preisrobot.service.internal.AmazonImageGrabber;
import de.preisrobot.service.internal.PreisRobotParserException;

public class IconarchiveImageParser {

	public static void main(String[] args) throws Exception {
		IconarchiveImageParser d = new IconarchiveImageParser();
		d.parse("http://www.iconarchive.com/show/stock-folder-icons-by-hamzasaleem.html");
//		
//		for (int i = 19; i < 36; i++) {
//			d.parse("http://www.iconarchive.com/show/fugue-icons-by-yusuke-kamiyamane."+i+".html");
//		}
	}

	public List<Artikel> parse(String sourceUrlString) throws Exception {

		List<Artikel> list = new ArrayList<Artikel>();

		if (sourceUrlString == null || sourceUrlString.length() == 0)
			throw new RuntimeException("Using default argument of \""
					+ sourceUrlString + '"');

		HttpClient client = HttpClientFactory.getHttpClient();
		GetMethod method = HttpClientFactory.createGETMethod(sourceUrlString);
		client.executeMethod(method);

		try {

			InputStream in = method.getResponseBodyAsStream();
			Source s = new Source(in);
			
//			List<Element> elementById = s.getAllElementsByClass("lastitem");
			List<Element> elementById = s.getAllElementsByClass("icondetail");
			
	  
			for (Element element : elementById) {
				
				List<Element> allElements = element.getAllElements("img");
				Element element2 = allElements.get(0);
				
				String attributeValue = element2.getAttributeValue("src");
				System.out.println(attributeValue);
				 
				URL url = new URL(attributeValue);
				String file = url.getFile();
				File f = new File(file);

				System.out.println(file);
				File file2 = new File("d:\\temp", f.getName());
				if (file2.exists()) {
					file2 = new File("d:\\temp", f.getName()
							+ System.currentTimeMillis()+FileHelper.getFileEnding(f.getName()));
				}
				FileHelper.saveIMage(url, file2);
			}

		} catch (PreisRobotParserException e) {
			e.printStackTrace();
			throw e;
		} catch (Exception e) {

			e.printStackTrace();

		} finally {

			method.releaseConnection();
		}
		return list;
	}
}
